/*
 * @Author: seanyan
 * @Date:   2021-09-13 16:21:33
 * @Last Modified by:   qinuoyun
 * @Last Modified time: 2021-10-16 10:34:12
 */
//加载路由
const router = require('koa-router')();
//加载URL
const url = require('url');
//加载工具
const util = require('util');
//创建API接口前缀
router.prefix('/auto');

//创建执行的API接口
router.all('*', async (ctx, next) => {
    try {
        //处理URL常用常量
        define('$_URL', explode("/", trim(url.parse(ctx.url, true).path, "/")));
        define('$_POST', ctx.method === 'POST' ? ctx.request.body : []);
        define('$_GET', ctx.query || []);
        define('$_FILES', isset(ctx.request.files) ? ctx.request.files : []);
        define('$_METHOD', ctx.method);
        define('$_SERVER', ctx.headers);

        //处理跨域问题
        let origin = "*";
        if (ctx.headers.origin) {
            origin = rtrim(ctx.headers.origin, "/");
        }
        ctx.set("Access-Control-Allow-Origin", origin);
        ctx.set("Access-Control-Allow-Credentials", true)
        ctx.set("Access-Control-Allow-Headers", "Content-Type,Content-Length,Authorization,Accept,X-Requested-With");
        ctx.set("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
        ctx.set("Q-Powered-By", '1.0.0')

        //执行URL参数设置
        let argument = copy_data($_URL);
        let API = argument.shift();
        //判断第一个值是否为空
        API = API ? API : argument.shift();
        let Model = argument.shift();
        let Action = argument.shift().split('?').shift();

        //获取对应的API数据文件
        const instance = getApiFile(Model);
        //判断是否函数
        if (typeof instance == 'function') {
            try {
                const object = new instance(ctx, next);
                //设置执行方法名称
                const defaultAction = "action" + ucfirst(Action);
                //执行该对象方法且处理异步方法
                const returned = await object[defaultAction]();
                ctx.body = {
                    code: 0,
                    msg: "succeed",
                    data: returned
                }
            } catch (error) {
                throw error;
            }
        } else {
            throw new Error('API文件' + api_file + "非类文件或无module.exports输出");
        }
    } catch (error) {
        throw error;
    }
});

/**
 * 获取API文件
 * @return {[type]} [description]
 */
const getApiFile = function(Model) {
	//运算核心文件处理
    // const api_file = ROOT_DIR + DS + 'src' + DS + 'controllers' + DS + ucfirst(Model) + 'Controller.js';
    // if (is_file(api_file)) {
    //     delete require.cache[require.resolve(api_file)];
    //     return require(api_file);
    // } else {
    //     throw new Error('API文件' + api_file + "不存在,请检查");
    // }
}

module.exports = router;